package com.tdu.spider.biz.task;

import com.google.common.collect.Lists;
import com.tdu.spider.biz.service.same.SameApiService;
import com.tdu.spider.biz.service.same.SameChannelService;
import com.tdu.spider.dao.SameChannelActivityRepository;
import com.tdu.spider.model.SameChannelActivityDO;
import com.tdu.spider.model.SameChannelDO;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 统计在线人数
 *
 * @author tangdu
 * @version $: DaliySameOnLineTask.java, v 0.1 2018年01月26日 下午9:19 tangdu Exp $
 */
@Component
public class DaliySameOnLineTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(DaliySameOnLineTask.class);


    @Autowired
    SameChannelActivityRepository sameChannelActivityRepository;

    @Autowired
    SameChannelService sameChannelService;


    @Autowired
    private SameApiService sameApiService;

    @Scheduled(cron = "0 30 1,2,3,5,6,8,12,17,19,22,23 * * ?")
    public void 统计上线人数() {
        LOGGER.info("Scheduled.DaliySameOnLineTask.统计上线人数 定时任务:");
        List<SameChannelDO> channelInfoVOS = sameChannelService.getAll();

        List<SameChannelActivityDO> list = Lists.newArrayList();
        for (SameChannelDO channelInfoVO : channelInfoVOS) {
            try {
                Integer count = sameApiService.queryChannelCount(channelInfoVO.getId());
                SameChannelActivityDO sameChannelActivityDO = new SameChannelActivityDO();
                sameChannelActivityDO.setChannelId(channelInfoVO.getId());
                sameChannelActivityDO.setChannelName(channelInfoVO.getName());
                sameChannelActivityDO.setOnline(count);
                sameChannelActivityDO.setTime(new DateTime().toString("yyyy-MM-dd HH"));
            } catch (Exception e) {
                LOGGER.error("queryChannelCount", e);
                e.printStackTrace();
            }
        }
        sameChannelActivityRepository.saveAll(list);
        LOGGER.info("Scheduled.DaliySameOnLineTask.统计上线人数.end 定时任务:");

    }
}
